package meiyunting.shiwuzhaoling.controller;

import lombok.extern.slf4j.Slf4j;
import meiyunting.shiwuzhaoling.client.LostFoundServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Feign客户端演示控制器
 * 展示如何使用Feign客户端进行服务调用
 */
@Slf4j
@RestController
@RequestMapping("/api/feign")
public class FeignDemoController {

    @Autowired
    private LostFoundServiceClient lostFoundServiceClient;
    
    @Value("${server.port}")
    private String serverPort;
    
    /**
     * 使用Feign客户端获取实例信息
     * 演示基本的服务调用
     */
    @GetMapping("/instance-info")
    public Map<String, Object> getInstanceInfo() {
        log.info("【Feign演示】从端口 {} 发起获取实例信息请求", serverPort);
        System.out.println("【Feign演示】从端口 " + serverPort + " 发起获取实例信息请求");
        
        // 使用Feign客户端调用服务
        Map<String, Object> result = lostFoundServiceClient.getInstanceInfo();
        
        // 添加源端口信息
        Map<String, Object> response = new HashMap<>(result);
        response.put("sourcePort", serverPort);
        response.put("clientType", "Feign");
        
        log.info("【Feign演示】请求从端口 {} 路由到端口 {}", serverPort, result.get("port"));
        System.out.println("【Feign演示】请求从端口 " + serverPort + " 路由到端口 " + result.get("port"));
        
        return response;
    }
    
    /**
     * 获取用户的失物信息
     * 演示带参数的服务调用
     */
    @GetMapping("/lost-items/{userId}")
    public Map<String, Object> getUserLostItems(@PathVariable Long userId) {
        log.info("【Feign演示】从端口 {} 发起获取用户失物信息请求，用户ID: {}", serverPort, userId);
        
        // 使用Feign客户端调用服务
        List<Map<String, Object>> items = lostFoundServiceClient.getUserLostItems(userId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("userId", userId);
        response.put("items", items);
        response.put("count", items.size());
        response.put("sourcePort", serverPort);
        
        return response;
    }
    
    /**
     * 提交失物信息
     * 演示POST请求的服务调用
     */
    @PostMapping("/submit-lost")
    public Map<String, Object> submitLostItem(@RequestBody Map<String, Object> itemData) {
        log.info("【Feign演示】从端口 {} 发起提交失物信息请求", serverPort);
        
        // 添加来源信息
        itemData.put("sourcePort", serverPort);
        
        // 使用Feign客户端调用服务
        Map<String, Object> result = lostFoundServiceClient.submitLostItem(itemData);
        
        // 添加源端口信息
        Map<String, Object> response = new HashMap<>(result);
        response.put("sourcePort", serverPort);
        
        return response;
    }
    
    /**
     * 多次调用服务，测试负载均衡
     */
    @GetMapping("/test-loadbalancer/{times}")
    public Map<String, Object> testLoadBalancer(@PathVariable int times) {
        log.info("【Feign负载均衡测试】从端口 {} 发起 {} 次调用", serverPort, times);
        
        Map<String, Object> result = new HashMap<>();
        Map<String, Integer> portCounts = new HashMap<>();
        
        for (int i = 0; i < times; i++) {
            Map<String, Object> response = lostFoundServiceClient.getInstanceInfo();
            String port = response.get("port").toString();
            portCounts.put(port, portCounts.getOrDefault(port, 0) + 1);
            
            log.info("【Feign请求 #{} 结果】请求被路由到端口: {}", i+1, port);
        }
        
        result.put("sourcePort", serverPort);
        result.put("statistics", portCounts);
        result.put("totalCalls", times);
        
        // 打印统计结果
        portCounts.forEach((port, count) -> {
            double percentage = (double) count / times * 100;
            log.info("【Feign负载均衡统计】端口 {} 收到 {} 个请求 ({}%)", 
                    port, count, String.format("%.2f", percentage));
        });
        
        return result;
    }
} 
 